package demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-04-10
 * Time: 21:00
 */
public class MyListnode {
    public class ListNode{
        public ListNode next;
        public int val;
        public void Node(){

        }
        public void Node(String data){


        }

        public ListNode head;
    }


    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <= 0 || head == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0;i < k -1;i++){
            fast = fast.next;
            if(fast == null){
                return null;
            }
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }


    public ListNode FindKthToTail1(ListNode head,int k) {
        if(head == null || k<=0){
            return null;
        }

        ListNode former = head;
        ListNode latter = head;

        //former先走n步
        for(int i=0;i<k;i++){
            if(former == null){   //n大于链表长度时
                return null;
            }
            former = former.next;
        }

        //former和latter一起走，当former为null时，latter恰好是倒数第k个节点
        while(former!=null){
            former = former.next;
            latter = latter.next;
        }

        return latter;
    }
}
